package com.xiaode.controller.app.myCampus.happy;

import java.time.LocalDateTime;
import java.util.List;
import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.Admin;
import com.xiaode.common.model.Chapter;
import com.xiaode.common.model.Curriculum;
import com.xiaode.common.model.CurriculumComment;
import com.xiaode.common.model.CurriculumCommentLike;
import com.xiaode.common.model.CurriculumMod;
import com.xiaode.common.model.CurriculumUser;
import com.xiaode.common.model.Division;
import com.xiaode.common.model.DivisionFile;
import com.xiaode.common.model.Student;
import com.xiaode.common.model.UserAccount;
import com.xiaode.common.model.VideoUserRate;
import com.xiaode.common.model.dto.curriculum.ChapterDTO;
import com.xiaode.common.model.dto.curriculum.DivisionDTO;
import com.xiaode.common.model.dto.curriculum.DivisionFileDTO;
import com.xiaode.common.model.dto.curriculum.TogetherChapterDTO;
import com.xiaode.common.model.dto.curriculum.TogetherDivisionDTO;
import com.xiaode.common.model.dto.curriculum.TogetherDivisionFileDTO;
import com.xiaode.exce.EnumError;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;

public class HappyCurriculumService {
	
	public Ret getCurriculumMod() throws Exception {
		List<CurriculumMod> cmList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE hierarchy = 0 ORDER BY num ASC");
        return Ret.ok("cmList", cmList);
    }
	
	public Ret getCurriculumModAll() throws Exception {
		List<CurriculumMod> cmList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE hierarchy = 0 ORDER BY num ASC");
		for(CurriculumMod cm : cmList){
			List<CurriculumMod> cmZList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE parent_id = ?", cm.getId());
			cm.put("cmZList", cmZList);
		}
        return Ret.ok("cmList", cmList);
    }
	
	public Ret getCurriculumModSon(Integer modId) throws Exception {
		List<CurriculumMod> cmZList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE parent_id = ?", modId);
        return Ret.ok("cmZList", cmZList);
    }
	
	public Ret getRecommend() throws Exception {
		List<Curriculum> cmList = Curriculum.dao.find("SELECT c.*,(SELECT `name` FROM admin WHERE id = c.creator_id) userName FROM curriculum c WHERE c.is_good = 1 AND c.state = 2 ORDER BY c.view_num DESC,c.update_time DESC");
		return Ret.ok("cmList", cmList);
    }
	
	public Ret getTeacherPublicCurriculum(Integer publisherId, Integer page, Integer limit) throws Exception {
		Page<Record> cmPage = Db.paginate(page, limit, "SELECT c.*,(SELECT `name` FROM admin WHERE id = c.creator_id) userName ", "FROM curriculum c WHERE c.state = 2 AND c.publisher_id = ? ORDER BY c.view_num DESC,c.update_time DESC", publisherId);        	
		return Ret.ok("cmPage", cmPage);
    }
	
	public Ret getNewUpdateCurriculum(Integer page, Integer limit) throws Exception {
		Page<Record> cPage = Db.paginate(page, limit, "SELECT c.id,c.`name`,c.picture,c.labels,c.update_time,c.lecturer ", "FROM curriculum c WHERE c.state = 2 ORDER BY c.update_time DESC");
        return Ret.ok("cPage", cPage);
    }
	
	public Ret getCurriculumByMod(Integer modId, Integer page, Integer limit) throws Exception {
		Page<Record> cPage = Db.paginate(page, limit, "SELECT c.id,c.`name`,c.picture,c.labels,c.update_time,c.view_num,c.lecturer "," FROM curriculum c WHERE c.mod_id = ? AND c.state = 2 ORDER BY c.view_num DESC,c.update_time DESC", modId);
        return Ret.ok("cPage", cPage);
    }
	
	public Ret getCurriculumInfo(Integer userId, Integer userType, Integer curriculumId) throws Exception {
		Curriculum c = Curriculum.dao.findFirst("SELECT c.* FROM curriculum c WHERE c.id = ? AND c.state = 2", curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		//记录我学习过的课程
		if(userType == Const.UserType.student) {
			CurriculumUser cu = CurriculumUser.dao.findFirst("SELECT * FROM curriculum_user WHERE curriculum_id = ? AND user_id = ?", c.getId(), userId);
			if(BeanUtil.isEmpty(cu)) {
				cu = new CurriculumUser();
				cu.setCurriculumId(curriculumId);
				cu.setUserId(userId);
				cu.setAddTime(LocalDateTime.now());
				cu.save();
			}
		}
		return Ret.ok("curriculum", c);
    }
	
	public Ret getChapterDivision(Integer curriculumId) throws Exception {
		List<Chapter> chapterList = Chapter.dao.find("SELECT * FROM chapter WHERE curriculum_id = ? ", curriculumId);
		for(Chapter chapter : chapterList) {
			List<Division> divisionList = Division.dao.find("SELECT * FROM division WHERE chapter_id = ?", chapter.getId());
			for(Division division : divisionList) {
				List<DivisionFile>  divisionFileList = DivisionFile.dao.find("SELECT * FROM division_file WHERE division_id = ?", division.getId());
				division.put("divisionFileList", divisionFileList);
			}
			chapter.put("divisionList", divisionList);
		}
		return Ret.ok("chapterList", chapterList);
    }
	
	public Ret getMyCurriculum(Integer userId, Integer studentId, Integer page, Integer limit) throws Exception {
		userId = studentId == null ? userId : studentId;
		Page<Record> cPage = Db.paginate(page, limit, "SELECT c.id,c.`name`,c.picture,c.labels,a.`name` teacherName ", "FROM curriculum_user cu LEFT JOIN curriculum c ON c.id = cu.curriculum_id LEFT JOIN admin a ON a.id = c.creator_id WHERE cu.user_id = ? AND c.id IS NOT NULL", userId);
		return Ret.ok("cPage", cPage);
    }
	
	public Ret getVideoRate(Integer userId, Integer userType, Integer divisionFileId) throws Exception {
		//记录观看次数
		DivisionFile df = DivisionFile.dao.findById(divisionFileId);
		if(BeanUtil.isNotEmpty(df)) {
			df.setViewNum(df.getViewNum() + 1);
			df.update();
			Integer chapterId = Db.queryInt("SELECT chapter_id FROM division WHERE id = ?", df.getDivisionId());
			if(chapterId != null) {
				Integer curriculumId = Db.queryInt("SELECT curriculum_id FROM chapter WHERE id = ?", chapterId);
				if(curriculumId != null) {
					Curriculum curriculum = Curriculum.dao.findById(curriculumId);
					if(BeanUtil.isNotEmpty(curriculum)) {
						curriculum.setViewNum(curriculum.getViewNum() + 1);
						curriculum.update();
					}
				}
			}
		}
		if(userType == Const.UserType.student) {
			VideoUserRate vur = VideoUserRate.dao.findFirst("SELECT * FROM video_user_rate WHERE division_file_id = ? AND user_id = ?", divisionFileId, userId);
			return Ret.ok("vur", vur);
		}
		return Ret.ok();
    }
	
	public Ret getGoodComment() throws Exception {
		List<CurriculumComment> ccList = CurriculumComment.dao.template("goodComment").find();
		//获取评论人信息
		for(CurriculumComment cc : ccList) {
			UserAccount ua = UserAccount.dao.findById(cc.getCreateAccountId());
			if(ua.getUserType() == 2) {
				Student u = Student.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM student WHERE accountId = ? ", ua.getId());
				cc.put("u", u);
			}
			if(ua.getUserType() == 1) {
				Admin u = Admin.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM admin WHERE accountId = ? ", ua.getId());
				cc.put("u", u);
			}
		}
        return Ret.ok("ccList", ccList);
    }
	
	public Ret getComment(Integer accountIdMy ,Integer curriculumId, Integer page, Integer limit) throws Exception {
		Curriculum c = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		Page<CurriculumComment> ccPage = CurriculumComment.dao.paginate(page, limit, "SELECT *", " FROM curriculum_comment WHERE curriculum_id = ? AND stratum = 1 ORDER BY updateTime DESC", curriculumId);
		List<CurriculumComment> ccList =ccPage.getList();
		for(CurriculumComment cc : ccList) {
			//获取用户信息
			UserAccount ua = UserAccount.dao.findById(cc.getCreateAccountId());
			if(ua.getUserType() == 2) {
				Student u = Student.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM student WHERE accountId = ? ", ua.getId());
				cc.put("u", u);
			}
			if(ua.getUserType() == 1) {
				Admin u = Admin.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM admin WHERE accountId = ? ", ua.getId());
				cc.put("u", u);
			}
			//获取，用户是否点过赞
			CurriculumCommentLike ccl = CurriculumCommentLike.dao.findFirst("SELECT id FROM curriculum_comment_like WHERE comments_id = ? AND like_account_id = ?", cc.getId(), accountIdMy);
			if(BeanUtil.isNotEmpty(ccl)) {
				cc.put("isLike", true);  
			}else {
				cc.put("isLike", false);  
			}
			//获取所有子评论
			List<CurriculumComment> ccZList = CurriculumComment.dao.find("SELECT * FROM curriculum_comment WHERE top_comments_id = ? AND stratum = 2 AND id != ?", cc.getId(), cc.getId());
			for(CurriculumComment ccZ : ccZList) {
				CurriculumComment ccf = CurriculumComment.dao.findById(ccZ.getCommentsId());
				UserAccount uaf = UserAccount.dao.findById(ccf.getCreateAccountId());
				if(uaf.getUserType() == 2) {
					Student u = Student.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM student WHERE accountId = ? ", uaf.getId());					
					ccZ.put("uf", u);
				}
				if(uaf.getUserType() == 1) {
					Admin u = Admin.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM admin WHERE accountId = ? ", uaf.getId());
					ccZ.put("uf", u);
				}
				
				UserAccount uaZ = UserAccount.dao.findById(ccZ.getCreateAccountId());
				if(uaZ.getUserType() == 2) {
					Student u = Student.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM student WHERE accountId = ? ", uaZ.getId());					
					ccZ.put("u", u);
				}
				if(uaZ.getUserType() == 1) {
					Admin u = Admin.dao.findFirst("SELECT `name`,user_type,avatarUrl FROM admin WHERE accountId = ? ", uaZ.getId());
					ccZ.put("u", u);
				}
				//获取，用户是否点过赞
				CurriculumCommentLike cclZ = CurriculumCommentLike.dao.findFirst("SELECT id FROM curriculum_comment_like WHERE comments_id = ? AND like_account_id = ?", ccZ.getId(), accountIdMy);
				if(BeanUtil.isNotEmpty(cclZ)) {
					ccZ.put("isLike", true);  
				}else {
					ccZ.put("isLike", false);  
				}
			}
			cc.put("ccZList", ccZList);
		}
		
		return Ret.ok("ccPage", ccPage).set("interactionNum", c.getInteractionNum());
    }
	
	@Before(Tx.class)
	public Ret createComment(Integer accountId, Integer userType, Integer curriculumId, String comment, Integer commentId, Integer topCommentId) throws Exception {
		Curriculum c = Curriculum.dao.findFirst("SELECT * FROM curriculum WHERE id = ? AND state = 2", curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		//是否是回复
		if (BeanUtil.isNotEmpty(commentId) && BeanUtil.isNotEmpty(topCommentId)) {
			CurriculumComment cc = CurriculumComment.dao.findById(commentId);
            if (BeanUtil.isEmpty(cc)) {
                return Ret.fail().set("error", EnumError.COMMENTS_HAS_DELETE.getObj());
            }
        }
		CurriculumComment cc = new CurriculumComment();
		cc.setCreateAccountId(accountId);
		cc.setComments(comment);
		cc.setCurriculumId(curriculumId);
		if(BeanUtil.isNotEmpty(commentId) && BeanUtil.isNotEmpty(topCommentId)) {
			cc.setStratum(Const.campusShareCommentStratum.REPLY);
			cc.setCommentsId(commentId);
			cc.setTopCommentsId(topCommentId);
		}else {
			cc.setStratum(Const.campusShareCommentStratum.SHARE);
		}
		cc.setUserType(userType);
		cc.setUpdateTime(LocalDateTime.now());
		cc.setAddTime(LocalDateTime.now());
		cc.save();
		//添加上一级的互动次数
		//1.课程互动次数
		c.setInteractionNum(c.getInteractionNum() + 1);
		c.update();
		//2.评论互动次数（需要递归找上级）
		addInteractionNumCommentDG(commentId);
		
        return Ret.ok();
    }
	public void addInteractionNumCommentDG(Integer commentId) {
		CurriculumComment cc = CurriculumComment.dao.findById(commentId);
		if(BeanUtil.isEmpty(cc)) {
			return;
		}
		cc.setInteractionNum(cc.getInteractionNum() + 1);
		cc.update();
		if(cc.getCommentsId() != null) {
			addInteractionNumCommentDG(cc.getCommentsId());
		}
		return;
	}
	
	@Before(Tx.class)
	public Ret deleComment(Integer accountId, Integer commentId) {
		CurriculumComment cc = CurriculumComment.dao.findById(commentId);
		if(BeanUtil.isEmpty(cc)) {
			return Ret.fail().set("error", EnumError.COMMENT_NULL.getObj());
		}
		if(!cc.getCreateAccountId().equals(accountId)) {
			return Ret.fail().set("error", EnumError.COMMENT_DELE_ME.getObj());
		}
		//还要处理所有父级的互动（评论）数量
		Integer interactionNum = cc.getInteractionNum();
		Curriculum c = Curriculum.dao.findById(cc.getCurriculumId());
		c.setInteractionNum(c.getInteractionNum() - (interactionNum + 1));
		c.update();
		changeParentInteractionNumDG(interactionNum + 1, cc);
		
		//删除这个评论下的所有回复(需要递归)
		delecCommentDG(commentId);
		
		//删除
		cc.delete();
		
		return Ret.ok();
	}
	public void delecCommentDG(Integer commentId){
		List<CurriculumComment> ccZList = CurriculumComment.dao.find("SELECT * FROM curriculum_comment WHERE comments_id = ?", commentId);
		for(CurriculumComment ccZ : ccZList) {
			ccZ.delete();
			delecCommentDG(ccZ.getId());
		}
	}
	public void changeParentInteractionNumDG(Integer interactionNum, CurriculumComment cc) {
		if(cc.getTopCommentsId() != null) {
			CurriculumComment ccP = CurriculumComment.dao.findById(cc.getCommentsId());
			if(BeanUtil.isNotEmpty(ccP)) {
				ccP.setInteractionNum(ccP.getInteractionNum() - interactionNum);
				ccP.update();
				changeParentInteractionNumDG(interactionNum, ccP);
			}
		}
		
	}
	
	
	
	@Before(Tx.class)
	public Ret praiseComment(Integer accountId, Integer commentId) {
		CurriculumComment cc = CurriculumComment.dao.findById(commentId);
		if(BeanUtil.isEmpty(cc)) {
			return Ret.fail().set("error", EnumError.COMMENT_NULL.getObj());
		}
		CurriculumCommentLike ccl = CurriculumCommentLike.dao.findFirst("SELECT * FROM curriculum_comment_like WHERE comments_id = ? AND like_account_id = ?", commentId, accountId);
		if(BeanUtil.isEmpty(ccl)) {
			ccl = new CurriculumCommentLike();
			ccl.setCommentsId(commentId);
			ccl.setLikeAccountId(accountId);
			ccl.setAddTime(LocalDateTime.now());
			ccl.save();
			cc.setPraiseNum(cc.getPraiseNum() + 1);
		}else {
			ccl.delete();
			cc.setPraiseNum(cc.getPraiseNum() - 1);
		}
		cc.update();
		return Ret.ok();
	}

	@Before(Tx.class)
	public Ret createCurriculum(Integer userId, Integer userType, Integer modId, String name, String lecturerName, String labels, String brief, String picture, String chapterDivision) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		CurriculumMod cm = CurriculumMod.dao.findById(modId);
		if(BeanUtil.isEmpty(cm)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_MOD_NULL.getObj());
		}
		//先添加课程
		Curriculum c = new Curriculum();
		c.setModId(modId);
		c.setName(name);
		c.setLecturer(lecturerName);
		c.setBrief(brief);
		c.setLabels(labels);
		c.setPicture(picture);
		c.setCreatorId(userId);
		c.setPublisherId(userId);
		c.setAddTime(LocalDateTime.now());
		c.setState(2);
		c.setUpdateTime(LocalDateTime.now());
		c.save();
		//再添加章
		List<ChapterDTO> chapterDTOList = JSONUtil.toList(chapterDivision, ChapterDTO.class);
		for(ChapterDTO chapterDTO : chapterDTOList) {
			Chapter chapter = new Chapter();
			chapter.setCurriculumId(c.getId());
			chapter.setName(chapterDTO.getName());
			chapter.setAddTime(LocalDateTime.now());
			chapter.setCreatorId(userId);
			chapter.setUpdateTime(LocalDateTime.now());
			chapter.save();
			//最后添加节
			List<DivisionDTO> divisionDTOList = chapterDTO.getDivisionDTOList();
			for(DivisionDTO divisionDTO : divisionDTOList) {
				Division division = new Division();
				division.setChapterId(chapter.getId());
				division.setName(divisionDTO.getName());
				division.setAddTime(LocalDateTime.now());
				division.setCreatorId(userId);
				division.setUpdateTime(LocalDateTime.now());
				division.save();
			}
		}
		return Ret.ok();
	}
	
	public Ret curriculumRecordNameList(Integer userId, Integer userType){
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		List<Curriculum> cList = Curriculum.dao.find("SELECT id,`name` FROM curriculum WHERE creator_id = ? ORDER BY update_time DESC", userId);
		return Ret.ok("nameList", cList);
	}
	
	public Ret curriculumRecord(Integer userId, Integer userType, Integer curriculumId){
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Curriculum c = Curriculum.dao.findFirst("SELECT c.labels,c.brief,c.picture,cm.`name` modNameZ,cm2.`name` modName FROM curriculum c LEFT JOIN curriculum_mod cm ON c.mod_id = cm.id LEFT JOIN curriculum_mod cm2 ON cm.parent_id = cm2.id WHERE c.id = ? AND c.creator_id = ?", curriculumId, userId);		
		return Ret.ok("curriculum", c);
	}
	
	public Ret addDivision(Integer userId, Integer userType, Integer chapterId, String name) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Chapter c = Chapter.dao.findById(chapterId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CHAPTER_NULL.getObj());
		}
		Division division = new Division();
		division.setChapterId(chapterId);
		division.setName(name);
		division.setAddTime(LocalDateTime.now());
		division.setCreatorId(userId);
		division.setUpdateTime(LocalDateTime.now());
		division.save();
		return Ret.ok();
	}
	
	public Ret addChapter(Integer userId, Integer userType, Integer  curriculumId, String name) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Curriculum c = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		Chapter chapter = new Chapter();
		chapter.setCurriculumId(curriculumId);
		chapter.setName(name);
		chapter.setAddTime(LocalDateTime.now());
		chapter.setCreatorId(userId);
		chapter.setUpdateTime(LocalDateTime.now());
		chapter.save();
		return Ret.ok();
	}
	
	public Ret addDivisionFile(Integer userId, Integer userType, String divisionFileStr) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		List<DivisionFileDTO> divisionFileDTOList = JSONUtil.toList(divisionFileStr, DivisionFileDTO.class);
		for(DivisionFileDTO dto : divisionFileDTOList) {
			Division c = Division.dao.findById(dto.getDivisionId());
			if(BeanUtil.isEmpty(c)) {
				return Ret.fail().set("error", EnumError.CHAPTER_NULL.getObj());
			}
			DivisionFile df = new DivisionFile();
			df.setDivisionId(dto.getDivisionId());
			df.setName(dto.getName());
			df.setAddTime(LocalDateTime.now());
			df.setCreatorId(userId);
			df.setUrl(dto.getUrl());
			df.setIsVideo(dto.getIsVideo());
			df.setSize(dto.getSize());
			df.save();
		}
		return Ret.ok();
	}
	
	@Before(Tx.class)
	public Ret addChapterDivisionFile(Integer userId, Integer userType, Integer curriculumId, String chapterDivisionFile) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Curriculum c = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		//添加章
		List<TogetherChapterDTO> togetherChapterDTOList = JSONUtil.toList(chapterDivisionFile, TogetherChapterDTO.class);
		for(TogetherChapterDTO togetherChapterDTO : togetherChapterDTOList) {
			Chapter chapter = new Chapter();
			chapter.setCurriculumId(c.getId());
			chapter.setName(togetherChapterDTO.getName());
			chapter.setAddTime(LocalDateTime.now());
			chapter.setCreatorId(userId);
			chapter.setUpdateTime(LocalDateTime.now());
			chapter.save();
			//添加节
			List<TogetherDivisionDTO> togetherDivisionDTOList = togetherChapterDTO.getTogetherDivisionDTO();
			for(TogetherDivisionDTO togetherDivisionDTO : togetherDivisionDTOList) {
				Division division = new Division();
				division.setChapterId(chapter.getId());
				division.setName(togetherDivisionDTO.getName());
				division.setAddTime(LocalDateTime.now());
				division.setCreatorId(userId);
				division.setUpdateTime(LocalDateTime.now());
				division.save();
				//添加文件
				List<TogetherDivisionFileDTO> togetherDivisionFileDTOList = togetherDivisionDTO.getTogetherDivisionFileDTO();
				for(TogetherDivisionFileDTO togetherDivisionFileDTO : togetherDivisionFileDTOList){
					DivisionFile df = new DivisionFile();
					df.setDivisionId(division.getId());
					df.setName(togetherDivisionFileDTO.getName());
					df.setAddTime(LocalDateTime.now());
					df.setCreatorId(userId);
					df.setUrl(togetherDivisionFileDTO.getUrl());
					df.setIsVideo(togetherDivisionFileDTO.getIsVideo());
					df.setSize(togetherDivisionFileDTO.getSize());
					df.save();
				}
			}
		}
		return Ret.ok();
	}
	
	@Before(Tx.class)
	public Ret deleCurriculum(Integer userId, Integer userType, Integer curriculumId){
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Curriculum curriculum = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isNotEmpty(curriculum)){
			List<Chapter> cList = Chapter.dao.find("SELECT * FROM chapter WHERE curriculum_id = ?", curriculum.getId());
			for(Chapter c : cList) {
				List<Division> dList = Division.dao.find("SELECT id FROM division WHERE chapter_id = ?", c.getId());
				for(Division d : dList) {
					Db.delete("DELETE FROM division_file WHERE division_id = ?", d.getId());
					d.delete();
				}
				c.delete();
			}
			curriculum.delete();
		}
		return Ret.ok();
	}
	
	@Before(Tx.class)
	public Ret deleChapter(Integer userId, Integer userType, Integer chapterId) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Chapter c = Chapter.dao.findById(chapterId);
		if(BeanUtil.isNotEmpty(c)){
			List<Division> dList = Division.dao.find("SELECT id FROM division WHERE chapter_id = ?", c.getId());
			for(Division d : dList) {
				Db.delete("DELETE FROM division_file WHERE division_id = ?", d.getId());
				d.delete();
			}
			c.delete();
		}
		return Ret.ok();
	}
	
	@Before(Tx.class)
	public Ret deleDivision(Integer userId, Integer userType, Integer divisionId) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		Division d = Division.dao.findById(divisionId);
		if(BeanUtil.isNotEmpty(d)){
			Db.delete("DELETE FROM division_file WHERE division_id = ?", d.getId());
			d.delete();
		}
		return Ret.ok();
	}
	
	public Ret deleDivisionFile(Integer userId, Integer userType, Integer divisionFileId) {
		if(userType != Const.UserType.admin) {
			return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
		}
		DivisionFile.dao.deleteById(divisionFileId);
		return Ret.ok();
	}
	
	public Ret recordUserViewRate(Integer userId, Integer userType, Integer divisionFileId, Integer rate){
		if(userType == Const.UserType.student) {
			VideoUserRate vur = VideoUserRate.dao.findFirst("SELECT * FROM video_user_rate WHERE division_file_id = ? AND user_id = ?", divisionFileId, userId);
			if(BeanUtil.isEmpty(vur)) {
				vur = new VideoUserRate();
				vur.setDivisionFileId(divisionFileId);
				vur.setRateN(rate);
				vur.setRateZ(rate);
				vur.setUserId(userId);
				vur.setDuration(rate);
				vur.save();
			}else {
				vur.setRateN(rate);
				if(rate > vur.getRateZ()) {
					vur.setRateZ(rate);
				}
				vur.update();
			}
		}
		return Ret.ok();
	}
	
	
	
	
	
	
	public static void main(String[] args) {
		String s = "[{\"name\":\"123\",\"divisionDTOList\":[{\"name\":\"456\"}]}    ]";
		List<ChapterDTO> chapterDTOList = JSONUtil.toList(s, ChapterDTO.class);
		System.out.println(chapterDTOList.get(0).getDivisionDTOList().get(0).getName());
	}
	
}
